package com.kude.manager;

import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;

import com.kude.dao.BaseDAO;
import com.kude.manager.support.IQuerySupport;


public abstract class AbstractManager<T,DAO extends BaseDAO<T, Integer>> implements IManager<T> {
	
	protected DAO dao;
	protected String tableName;
	
	public int getTotal() throws OperException {
		return dao.getTotal(tableName);
	}

	public int getTotal(IQuerySupport querySupport) throws OperException {
		if (querySupport == null) {
			throw new OperException("参数对象IQuerySupport不能为空");
		} else {
			return dao.getTotal(tableName,querySupport.encode());
		}
	}

	public void add(T obj) throws OperException{
		if(obj == null) {
			throw new OperException("添加对象obj不能为空");
		}
		dao.save(obj);
	}
	
	public void delete(T obj) throws OperException{
		if(obj == null) {
			throw new OperException("删除对象obj不能为空");
		}
		if(!isExist(obj)) {
			throw new OperException("删除对象obj在数据库中不存在");
		}
		dao.delete(obj);
	}
	
	public void delete(int id) throws OperException{
		dao.deleteById(id);
	}

	public T get(int id) throws OperException{
		return dao.getById(id);
	}
	
	public List<T> find(Criterion... criterion) throws OperException {
		return dao.findByCriteria(criterion);
	}
	public List<T> find(int offset, int limit, Criterion... criterion)
			throws OperException {
		return dao.findByCriteria(offset, limit, criterion);
	}
	
	public List<T> find(Order order, int offset, int limit,
			Criterion... criterion) throws OperException {
		return dao.findByCriteria(order, offset, limit, criterion);
	}
	
	public List<T> find(int offset, int limit) throws OperException {
		return dao.findByCriteria(offset, limit);
	}
	
	public List<T> find(Order order, int offset, int limit)
			throws OperException {
		return dao.findByCriteria(order, offset, limit);
	}
	
	public void update(T obj) throws OperException{
		if(obj == null) {
			throw new OperException("修改对象obj不能为空");
		}
		if(!isExist(obj)) {
			throw new OperException("修改对象obj在数据库中不存在");
		}
		dao.update(obj);
	}
}
